<?php

namespace App\Models\Shop;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;


class Category extends Model
{
    protected $guarded = [];
    //屏蔽掉表里的时间字段
    public $timestamps = false;

    //分类下有多个商品，多对多
    public function products(){
        return $this->belongsToMany('App\Models\Shop\Product');
    }

    //一级分类有很多二级分类
    public function children()
    {
        return $this->hasMany('App\Models\Shop\Category',
            'parent_id','id');
    }

    /***清除缓存
     * @return mixed
     */
    static function clear(){
        Cache::forget('shop_categories');
    }

    static function get_categories(){
        //设置缓存，存入shop_categories
        $categories = Cache::rememberForever('shop_categories', function() {
            return self::with([
                'children'=>function($query){
                    $query->orderBy('sort_order');//二级分类排序
                }
            ])->where('parent_id',0)->orderBy('sort_order')->get();
        });

        return $categories;
    }

    /***检查是否有二级分类
     * @param $id
     * @return bool
     */
//    static function check_children($id){
//        $category = self::with('children')->find($id);
//        if($category->children->isEmpty()){
//            return true;
//        }
//        return false;
//    }
    /***
     * @return mixed搜索分类时，屏蔽掉没有商品的分类
     */
    static function filter_categories(){
        $categories = self::has('children.products')->with([
            'children' => function ($query) {
                $query->has('products');
            }
        ])->get();
        return $categories;
    }

    /**
     * 检查当前分类是否有商品
     */
    static function check_products($id)
    {
        $category = self::with('products')->find($id);
        if ($category->products->isEmpty()) {
            return true;
        }
        return false;
    }
}
